/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年4月10日    li.shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi.framework.oval;

import java.lang.reflect.Method;

import net.sf.oval.ConstraintViolation;
import net.sf.oval.exception.ConstraintsViolatedException;
import net.sf.oval.guard.Guard;
import net.sf.oval.internal.util.Invocable;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import com.jimi.exception.ErrorCode;
import com.jimi.framework.context.SpringContextHolder;
import com.jimi.framework.utils.ResultModel;

/**
 * @FileName MyGuard.java
 * @Description: 整合oval校验框架，有国际化时提示国际化信息
 *
 * @Date 2017年4月10日 下午2:54:41
 * @author li.shangzhi
 * @version 1.0
 */
public class MyGuard extends Guard {

	private final Logger logger = LoggerFactory.getLogger(MyGuard.class);

	@Override
	public Object guardMethod(Object guardedObject, final Method method, final Object[] args, final Invocable invocable) throws Throwable {
		Object result = null;
		try {
			result = super.guardMethod(guardedObject, method, args, invocable);
		} catch (ConstraintsViolatedException ex) {
			ConstraintViolation[] constraintViolations = ex.getConstraintViolations();
			String errorCode = "";
			for (ConstraintViolation constraintViolation : constraintViolations) {
				logger.info(constraintViolation.getCheckName() + "===" + constraintViolation.getMessage());
				logger.info(constraintViolation.getErrorCode() + "===" + constraintViolation.getMessageTemplate());
				result = constraintViolation.getMessage();
				errorCode = constraintViolation.getErrorCode();
				break;
			}
			String msg = String.valueOf(result);
			if(StringUtils.isBlank(msg)) {
				msg = getErrorCode(errorCode);
			} else {
				MessageSource messageSource = SpringContextHolder.getBean(MessageSource.class);
				msg = messageSource.getMessage(String.valueOf(result), null, LocaleContextHolder.getLocale());
			}
			logger.error("请求[{}]方法时,参数校验不通过,msg={}", method.getName(), msg);
//			throw new SysParamsCheckException(ErrorCode.PARAM_ERROR, msg);
			return new ResponseEntity<>(new ResultModel(ErrorCode.PARAM_ERROR.getCode(), msg), HttpStatus.OK);
		}
		return result;
	}

	public String getErrorCode(String errorCode) {
		if (errorCode.indexOf("NotBlank") != -1) {
			return ErrorCode.PARAM_ERROR.getErrorMsg();
		}
		if (errorCode.indexOf("Length") != -1) {
			return ErrorCode.PARAM_ERROR.getErrorMsg();
		}
		if (errorCode.indexOf("Email") != -1) {
			return ErrorCode.PARAM_ERROR.getErrorMsg();
		}
		if (errorCode.indexOf("CheckWith") != -1) {
			return ErrorCode.PARAM_ERROR.getErrorMsg();
		}
		if (errorCode.indexOf("AssertURL") != -1) {
			return ErrorCode.PARAM_ERROR.getErrorMsg();
		}
		if (errorCode.indexOf("HasSubstring") != -1) {
			return ErrorCode.PARAM_ERROR.getErrorMsg();
		}
		if (errorCode.indexOf("Range") != -1) {
			return ErrorCode.PARAM_ERROR.getErrorMsg();
		}
		if (errorCode.indexOf("ValidateWithMethod") != -1) {
			return ErrorCode.PARAM_ERROR.getErrorMsg();
		}
		if (errorCode.indexOf("NotMatchPatternCheck") != -1) {
			return ErrorCode.PARAM_ERROR.getErrorMsg();
		}
		return ErrorCode.PARAM_ERROR.getErrorMsg();
	}

}
